package a.Handler;

import a.BeanFactory;
import a.annotation.Inject;
import a.InjectHandler;

import java.beans.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MethodInjectHandler implements InjectHandler {
    public void execute(Object target, Class<?> targetClass, BeanFactory factory) throws IllegalAccessException, InstantiationException {
        try {
            //Object o = targetClass.newInstance();
            BeanInfo beanInfo = Introspector.getBeanInfo(targetClass, Object.class);
            PropertyDescriptor[] psd = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor p:psd){
                Method writeMethod = p.getWriteMethod();
                if (writeMethod.isAnnotationPresent(Inject.class)){
                    String value = writeMethod.getAnnotation(Inject.class).value();
                    Object bean = factory.getBean(value);
                    writeMethod.invoke(target,bean);
                }
            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
